import scrapy
from scrapy.mail import MailSender
import datetime


class EmailNotificationExtension:
    def __init__(self, settings):
        self.settings = settings

    @classmethod
    def from_crawler(cls, crawler):
        ext = cls(crawler.settings)
        crawler.signals.connect(ext.spider_closed, signal=scrapy.signals.spider_closed)
        return ext

    def spider_closed(self, spider):
        spider.logger.info("Spider closed: %s" % spider.name)
        print("爬虫结束---------------------------------------------")
        today_date = datetime.date.today()
        mail_settings = {
            'MAIL_FROM': self.settings.get('MAIL_FROM', ''),
            'MAIL_HOST': self.settings.get('MAIL_HOST', 'smtp.qq.com'),
            'MAIL_PORT': self.settings.get('MAIL_PORT', 465),
            'MAIL_USER': self.settings.get('MAIL_USER', ''),
            'MAIL_PASS': self.settings.get('MAIL_PASS', ''),
            'MAIL_SSL': self.settings.get('MAIL_SSL', True)
        }
        settings = scrapy.settings.Settings(mail_settings, priority='project')
        mailer = MailSender.from_settings(settings)
        attach_name = "dangdangwang.json"
        mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        try:
            with open('dangdangwang.json', 'rb') as file_object:
                return mailer.send(
                    to=self.settings.getlist('MAIL_TO', ['2419078492@qq.com']),
                    subject=str(today_date) + u"dangdangwang.json;",
                    body='',
                    cc=self.settings.getlist('MAIL_CC', ['2419078492@qq.com']),
                    attachs=[(attach_name, mimetype, file_object)],
                    mimetype='text/plain'
                )

        except Exception as e:
            spider.logger.error(f"邮件发送失败: {e}")
        spider.logger.info("Spider closed: %s" % spider.name)